package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Override
    public ResponseResult findList(WmNewsPageReqDto dto) {
        return null;
    }

    /**
     * 保存文章的方法
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        if (null == dto || StringUtils.isNotEmpty(dto.getContent())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //保存或更新文章
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);

        if (null != dto.getImages()&& dto.getImages().size()>0){
            String images = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(images);
        }
        saveOrUpdateWmNew(wmNews);

        //如果用户保存的草稿则结束请求
        if (dto.getStatus().equals(WmNews.Status.NORMAL)){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //从内容中抽取所有的图片数据
        List<String> urls = ectractUrlInfo(dto.getContent());

        //保存内容中的图片和素材之间的关联关系
        saveRelativeInfoForContent(wmNews, urls, (short)0);

        return null;
    }

    /**
     * 保存内容中的图片和素材之间的关联关系
     * @param wmNews
     * @param urls
     * @param type
     */
    private void saveRelativeInfoForContent(WmNews wmNews, List<String> urls, short type) {
        //判断内容中是否有图片，如果有则保存关系
        if (urls.size()>0){
            //对urls里面的图片地址去重
            urls = urls.stream().distinct().collect(Collectors.toList());
            //根据url查询素材对象
            WmUser wmUser = WmThreadLocalUtil.getUser();
            if (null == wmUser){
                throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
            }

            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
                    .in(WmMaterial::getUrl, urls)
                    .eq(WmMaterial::getUserId, wmUser.getId()));

            //判断素材数据在使用的过程中是否被删除了
            if (null == wmMaterials || urls.size()!= wmMaterials.size()){
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
            }

            //保存素材和文章之间的关系
            List<Integer> ids = wmMaterials.stream().map(item -> item.getId()).collect(Collectors.toList());
            wmNewsMaterialMapper.saveRelations(wmNews.getId(), ids, type);

        }
    }

    /**
     * 从内容中抽取所有的图片数据
     * @param content
     * @return
     */
    private List<String> ectractUrlInfo(String content) {
        List<Map> list = JSON.parseArray(content, Map.class);
        List<String> result = new ArrayList<>();
        for (Map map : list) {
            if ("image".equals(map.get("type"))){
                result.add(map.get("value").toString());
            }
        }
        return result;
    }

    /**
     * 完成数据的保存或更新
     * @param wmNews
     */
    private void saveOrUpdateWmNew(WmNews wmNews) {
        if (null != wmNews.getId()){
            //更新
            //删除关联关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            //更新文章数据到文章表
            updateById(wmNews);
        }else {
            //新增
            save(wmNews);
        }
    }
}
